<?php

namespace Payment\Common\Fu\Data;

use Payment\Common\PayException;

/**
 * 退款
 *
 * Class RefundData
 *
 * @property string $order_no 商户系统订单号
 * @property string $refund_no 商户系统退款单号
 * @property int $total_fee 订单总金额，单位为分，只能为整数
 * @property int $refund_fee 退款总金额，不能大于订单总金额，单位为分，只能为整数
 * @property string $order_type 订单类型：ALIPAY(统一下单、条码支付、服务窗支付)，WECHAT(统一下单、条码支付、公众号支付)，UNIONPAY，BESTPAY(翼支付)
 * @property string $trade_date 原交易日期（Ymd，如：20190620）
 *
 * @package Payment\Common\Fu\Data
 */
class RefundData extends FuBaseData
{

    protected function checkDataParam()
    {
        if (empty($this->order_no) || mb_strlen($this->order_no) > 30) throw new PayException('商户系统订单号不能为空且长度不能超过30位');
        if (empty($this->refund_no) || mb_strlen($this->refund_no) > 30) throw new PayException('商户系统退款单号不能为空且长度不能超过30位');

        $totalFee = intval($this->total_fee ?? 0); //订单总金额
        $refundFee = intval($this->refund_fee ?? 0); //退款总金额
        if (empty($totalFee) || empty($refundFee)) throw new PayException('订单总金额或退款金额有误');
        if (bccomp($refundFee, $totalFee) === 1) throw new PayException('退款金额不能大于订单总金额');

        $tradeType = $this->order_type = $this->trade_type ?? ($this->order_type ?? '');
        if (empty($tradeType)) throw new PayException('订单类型有误(支持WECHAT、ALIPAY、UNIONPAY、BESTPAY)');
    }

    protected function buildData()
    {
        $signData = [
            'version' => $this->version,
            'ins_cd' => $this->institutionId, //机构号，接入机构在富友的唯一代码
            'mchnt_cd' => $this->merchantId, //商户号, 富友分配给二级商户的商户号
            'term_id' => $this->terminalId ?? '88888888', //终端号(没有真实终端号统一填88888888)
            'random_str' => $this->randomStr, //随机字符串
            'mchnt_order_no' => $this->order_no, //商户订单号, 商户系统内部的订单号（5到30个字符、只能包含字母数字，区分大小写)
            'order_type' => $this->order_type, //订单类型：ALIPAY(统一下单、条码支付、服务窗支付)，WECHAT(统一下单、条码支付、公众号支付)，UNIONPAY，BESTPAY(翼支付)
            'refund_order_no' => $this->refund_no, //商户撤销单号
            'total_amt' => $this->total_fee, //订单总金额
            'refund_amt' => $this->refund_fee, //退款总金额
            'operator_id' => $this->operator_id ?? '', //操作员
        ];
        if (!empty($this->reserved_fy_term_id)) $signData['reserved_fy_term_id'] = $this->reserved_fy_term_id; //富友终端号
        if (!empty($this->reserved_origi_dt)) $signData['reserved_origi_dt'] = $this->trade_date; //原交易日期（ yyyyMMdd ）！该值必定等于reserved_fy_settle_dt(富友接收交易时间。理论和合作方下单时间一致。微量夸日交易会不一致)。不填该值支持30天内的交易进行退款。填写该值，支持90天

        $this->retData = $signData;
    }

}